import path from 'path-browserify';
import { RawEditorSettings } from "tinymce";

import { blobToFile } from "@/utils/FileUtil";

var baseUrl = import.meta.env.BASE_URL;

interface FontInfo {
  label: string;
  font: string;
}

function formatPlugins(...plugins: string[]) {
  return plugins.join(" ");
}

function formatToolbar(...toolbars: string[][]) {
  return toolbars.map(list => `| ${list.join(" ")}`).join(" ");
}

function formatFontFormats(fontInfos: FontInfo[]) {
  return fontInfos.map(info => `${info.label}=${info.font}`).join(";");
}

// 配置信息
export default <RawEditorSettings>{

  base_url: baseUrl,

  convert_urls: false,

  /**
   * 语言路径
   */
  language_url: path.join(baseUrl, '/tinymce/langs/zh_CN.js'),

  /**
   * 语言
   */
  language: 'zh_CN',

  /**
   * 主题样式路径
   */
  skin_url: path.join(baseUrl, '/tinymce/skins/ui/oxide'),

  /**
   * 文本样式路径
   */
  content_css: path.join(baseUrl, '/tinymce/skins/content/default/content.min.css'),

  /**
   * 表情路径
   */
  emoticons_database_url: path.join(baseUrl, '/tinymce/emojis/emojis.min.js'),

  /**
   * 宽度
   */
  width: '100%',

  /**
   * 高度
   */
  height: 500,

  /**
   * 提示信息
   */
  placeholder: "请输入内容",

  /**
   * 插件
   */
  plugins: formatPlugins(
    'lists', 'pagebreak', 'charmap', 'emoticons',
    'save', 'preview', 'print', 'image', 'media', 'link',
    'powerpaste', 'anchor', 'codesample', 'table',
    'searchreplace', 'hr', 'insertdatetime',
    'wordcount', 'fullscreen', 'help', "autoresize",
    'advlist', 'formatpainter',
    'table-align'
  ),

  /**
   * 菜单栏
   */
  // menubar: formatMenubars("edit", "view", "format", "tools", "table"),
  menubar: false,

  /**
   * 工具栏
   */
  toolbar: formatToolbar(
    ['formatselect', 'fontselect', 'fontsizeselect', 'forecolor'],
    ['undo', 'redo', /* 'preview', */ 'fullscreen'],
    ['bold', 'italic', 'underline', 'strikethrough'],
    ['alignleft', 'aligncenter', 'alignright', 'alignjustify'],
    ['table-align-top', 'table-align-center', 'table-align-bottom'],
    ['outdent', 'indent', 'numlist', 'bullist', /* 'insertdatetime' */],
    ['table', 'backcolor', 'removeformat', 'formatpainter'],
    ['hr', 'searchreplace', 'charmap'],
    ['link'/* 'codesample', */ ],
  ),

  /**
   * 工具栏展开方式
   */
  toolbar_mode: 'sliding',

  /**
   * 是否允许拖动
   * true（仅允许改变高度）, false（完全不让你动）, 'both'（宽高都能改变，注意引号）
   */
  resize: true,

  /**
   * 底部状态栏
   */
  statusbar: true,

  /**
   * 是否显示版权信息
   */
  branding: false,

  /**
   * 是否允许黏贴图片
   */
  // paste_data_images: true,

  /**
   * 保留的黏贴 样式
   */

  /**
   * 添加扩展插件
   */
  external_plugins: {
    powerpaste: path.join(baseUrl, '/tinymce/powerpaste/plugin.min.js'),
  },
  powerpaste_word_import: 'propmt', // 参数可以是propmt, merge, clear，效果自行切换对比
  powerpaste_html_import: 'propmt', // propmt, merge, clear
  powerpaste_allow_local_images: true,

  formats: {
    underline: { inline: 'u', exact: true },
    strikethrough: { inline: 's', exact: true },
  },

  /**
   * 时间日期格式化
   */
  insertdatetime_formats: ['%H点%M分', '%Y年%m月%d日', '%Y年%m月%d日 %H点%M分', '%Y-%m-%d %H:%M'],

  // 默认使用base64格式
  // images_upload_handler: function(blobInfo, success, failure) {
  //   const maxSize = 2
  //   const blob = blobInfo.blob()

  //   if (blob.size / 1024 / 1024 > maxSize) {
  //     failure('图片大小不能超过' + maxSize + 'MB')
  //     return
  //   }

  //   const formData = new FormData()
  //   formData.append('file', blob, blobInfo.fileName)

  //   upload(formData).then(res => {
  //     success(res.data.fileUrl)
  //   }).catch(() => {
  //     failure('文件上传失败，请重试')
  //   })
  // }

  font_formats: formatFontFormats([
    { label: "微软雅黑", font: "微软雅黑" },
    { label: "宋体", font: "宋体" },
    { label: "黑体", font: "黑体" },
    { label: "仿宋", font: "仿宋" },
    { label: "楷体", font: "楷体" },
    { label: "隶书", font: "隶书" },
    { label: "幼圆", font: "幼圆" },
    { label: "Andale Mono", font: "andale mono,times" },
    { label: "Arial", font: "arial,helvetica,sans-serif" },
    { label: "Arial Black", font: "arial black,avant garde" },
    { label: "Book Antiqua", font: "book antiqua,palatino" },
    { label: "Comic Sans MS", font: "comic sans ms,sans-serif" },
    { label: "Courier New", font: "courier new,courier" },
    { label: "Georgia", font: "georgia,palatino" },
    { label: "Helvetica", font: "helvetica" },
    { label: "Impact", font: "impact,chicago" },
    { label: "Symbol", font: "symbol" },
    { label: "Tahoma", font: "tahoma,arial,helvetica,sans-serif" },
    { label: "Terminal", font: "terminal,monaco" },
    { label: "Times New Roman", font: "times new roman,times" },
    { label: "Trebuchet MS", font: "trebuchet ms,geneva" },
    { label: "Verdana", font: "verdana,geneva" },
    { label: "Webdings", font: "webdings" },
    { label: "Wingdings", font: "wingdings" },
  ]),

  /** 默认样式 */
  content_style: `
    html { min-width: fit-content; }
    p { margin: 0; }
    ul,ol { margin: 0; padding: 0; }
    ol { padding-left: 14px; }
    ul { padding-left: 17px; }
    pre { margin: 0; padding: 0; }
  `,

  /** 对象大小调整 */
  object_resizing: true,

  paste_preprocess: function (plugin: any, args: any) {
    if (args.content && args.content.includes("<table")) {
      const rootNode = document.createElement("div");
      rootNode.innerHTML = args.content;
      const allTables = rootNode.querySelectorAll('table');
      for (const tableEl of allTables) {
        tableEl.style.width = "100%";
        const tableAllChildren = tableEl.querySelectorAll('*') as NodeListOf<HTMLElement>;
        for (const childEl of tableAllChildren) {
          if (childEl.style.whiteSpace === 'nowrap') {
            childEl.style.whiteSpace = '';
          }
        }
      }
      args.content = rootNode.innerHTML;
    }
    if (args.content && args.content.includes("<img")) {
      const rootNode = document.createElement("div");
      rootNode.innerHTML = args.content;
      const allImages = rootNode.querySelectorAll('img');
      for (const imageEL of allImages) {
        if (imageEL.width > screen.width * 0.6) {
          imageEL.style.width = "100%";
        }
      }
      args.content = rootNode.innerHTML;
    }
  },

  // advlist_number_styles: "circled-alpha",

  contextmenu: 'copy paste | link image inserttable | cell row column deletetable',

  /** 创建表格默认属性 */ table_default_attributes: { border: '1' },

  images_upload_url: "/upload",

  images_upload_handler: async function (blobInfo, succFun, failFun) {
    var file = blobToFile(blobInfo.blob(), blobInfo.filename());
    try {
      succFun('/' + file);
    } catch (error) {
      failFun(error.message);
    }
  }

}
